package com.beilang.base.util;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import java.io.*;
import java.util.Calendar;


public class ZipUtil {

    public static String zipFile(File inFolder) {
        try {

            File outFolder = new File(inFolder.getAbsolutePath() + inFolder.getName() + ".zip");
            ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(outFolder)));
            out.setEncoding("gb2312");
            BufferedInputStream in = null;
            byte[] data = new byte[1000];
            String files[] = inFolder.list();
            for (String file : files) {
                in = new BufferedInputStream(new FileInputStream
                        (inFolder.getPath() + "/" + file), 1000);
                out.putNextEntry(new ZipEntry(file));
                int count;
                while ((count = in.read(data, 0, 1000)) != -1) {
                    out.write(data, 0, count);
                }
                out.closeEntry();
            }

            out.flush();
            if (in != null) in.close();
            if (out != null) out.close();
            System.gc();
            File pFolder = new File(Constant.FILEPATH);
            String cFolderStr[] = pFolder.list();
            for (String f : cFolderStr) {
                File cf = new File(pFolder.getPath() + "/" + f);
                if (cf.exists() && cf.isDirectory() && isOldFolder(cf)) {
                    String cfstr[] = cf.list();
                    for (String cstr : cfstr) {
                        String dcfstr = cf.getPath() + "/" + cstr;
                       // System.out.println(dcfstr);
                        File f1=new File(dcfstr);
                        if(f1.isFile()&&f1.exists()){
                            f1.delete();
                        }
                    }
                    cf.delete();
                }
            }
            return outFolder.getName();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean isOldFolder(File file){
        Long l1= file.lastModified();
        Long l2=DateUtil.add(DateUtil.getDate(), Calendar.DATE,-1).getTime();
        return l1<l2;
    }

}